# -*- coding: utf-8 -*-
import urllib2
import base64
import datetime
import hmac
import hashlib

distroid = ''
files = ['01/images-/favicon.ico','02/images-/test.gif']
awsacces = ''
awssecret = ''

host = 'cloudfront.amazonaws.com'
path = '/2010-11-01/distribution/%s/invalidation' % distroid
date = datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
auth = 'AWS %s:%s' %(awsacces,base64.b64encode(hmac.new(awssecret.encode('utf-8'),date.encode('utf-8'),hashlib.sha1).digest()))

# create xml data to post
data = ['<?xml version="1.0" encoding="UTF-8"?>']
data.append('<InvalidationBatch>') 
data.append('%s' % ''.join(['<Path>/%s</Path>' % f for f in files]))
data.append('<CallerReference>%s</CallerReference>' % date)
data.append('</InvalidationBatch>')
data = ''.join(data)

# define required http headers
headers = {
  'Host': host,
  'Authorization' : auth,
  'Date': date,
  'Content-Type': 'text/xml',
  'Content-Length': len(data),
}

# make REST request, capture 201 (success) response
request_url = 'https://%s%s' % (host, path)

#print auth
#print request_url
#print data

req = urllib2.Request(request_url, data, headers=headers)
try:
    response = urllib2.urlopen(req)
except urllib2.HTTPError, e:
    print e
